<!--
  * 退货单
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form :model="queryForm" labelAlign="left">
      <a-row :gutter="[8, 10]" class="smart-margin-bottom10">
        <a-col :span="{ sm: 7, md: 6 }">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="queryForm.create_time" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="业务员" class="smart-margin-bottom0">
            <Select name="Salesman" v-model:value="queryForm.salesman_id" placeholder="业务员" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="门店名称" class="smart-margin-bottom0">
            <Select name="Store" v-model:value="queryForm.store_id" placeholder="门店名称" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="入库仓库" name="warehouse_id" class="smart-margin-bottom0">
            <Select name="Warehouse" v-model:value="queryForm.warehouse_id" :fetch-params="selectFetchParams.warehouse" placeholder="请选择仓库" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery" v-privilege="'goods:query'">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
            <SearchFormCollapse v-model="expand" />
          </a-button-group>
        </a-col>
      </a-row>
      <template v-if="expand">
        <a-row :gutter="[8, 10]" class="smart-margin-bottom10">
          <a-col :span="4">
            <a-form-item label="配送方式" class="smart-margin-bottom0">
              <EnumSelect enum-name="IS_SELF" v-model:value="queryForm.is_self" placeholder="配送方式" @submit="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="结算方式" class="smart-margin-bottom0">
              <EnumSelect enum-name="RECEIVE_TYPE_ENUM" v-model:value="queryForm.payment_type" placeholder="结算方式" @submit="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="订单状态" class="smart-margin-bottom0">
              <EnumSelect enum-name="PROGRESS_TUHO_ENUM" v-model:value="queryForm.status" placeholder="订单状态" @submit="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="订单来源" class="smart-margin-bottom0">
              <EnumSelect enum-name="UNSETYLED_TYPE_ENUM" v-model:value="queryForm.source" placeholder="订单来源" @submit="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="单据编号" class="smart-margin-bottom0">
              <a-input v-model:value.trim="queryForm.no" placeholder="单据编号" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
      </template>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="addOrder" type="primary" v-privilege="'goods:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
        <a-button @click="showImportModal" primary v-privilege="'goods:importGoods'">
          <template #icon>
            <ImportOutlined />
          </template>
          导入
        </a-button>

        <a-button @click="onExport" type="primary" v-privilege="'goods:exportGoods'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table class="ant-table-striped" size="small" :dataSource="tableData" :columns="columns" :loading="tableLoading" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :row-selection="{}" :row-class-name="(record, index) => (Number(record.status) === 5 ? 'table-striped' : null)">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'no'">
            <CopyText :text="text">
              <a @click="detail(record)">{{ text }}</a>
            </CopyText>
          </template>
          <template v-if="column.dataIndex === 'detailAll'">
            <span v-for="type in uniqueTypes(record.detail)" :key="type">
              <a-tag :color="tagType[type]">{{ getDescByValue('GOODS_TYPE_ENUM', type) }}</a-tag>
            </span>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="tagType[text]">{{ getDescByValue('PROGRESS_TUHO_ENUM', Number(text)) }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'payment_type'">
            <span>{{ getDescByValue('RECEIVE_TYPE_ENUM', text) }}</span>
          </template>
          <template v-if="column.dataIndex === 'source'">
            <span>{{ getDescByValue('UNSETYLED_TYPE_ENUM', text) }}</span>
          </template>
          <template v-if="column.dataIndex === 'is_self'">
            <span>{{ getDescByValue('IS_SELF', text) }}</span>
          </template>
          <template v-if="column.dataIndex === 'warehouse_name'">
            <span
              >{{ record.warehouse?.name }}<span v-if="record.warehouse?.attribute_type">({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', record.warehouse?.attribute_type) }})</span>
            </span>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="detail(record)" type="link" style="color: #97999c" v-privilege="'goods:update'">详情</a-button>
              <template v-if="([6].includes(record.status) && record.is_self === 0) || (record.is_self === 1 && record.status === 1)">
                <a-button @click="addOrder(record)" type="link" v-privilege="'goods:update'">编辑</a-button>
                <a-button @click="returnCancel(record)" type="link" danger v-privilege="'goods:update'">取消</a-button>
              </template>
              <template v-if="record.status !== 5">
                <a-button @click="print(record)" type="link">打印</a-button>
              </template>
              <template v-if="record.status == 5">
                <a-button @click="deleteData(record.id, record.no)" type="link" danger v-privilege="'sale:return:del'">删除</a-button>
              </template>
            </div>
          </template>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <template v-for="item in columns">
                <template v-if="item.dataIndex === 'no'">
                  <a-table-summary-cell>总计</a-table-summary-cell>
                </template>
                <template v-if="item.dataIndex === 'detail_sum'">
                  <a-table-summary-cell>
                    <a-typography-text type="danger">{{ Number(total_amount.total_detail_sum).toFixed(2) }}</a-typography-text>
                  </a-table-summary-cell>
                </template>
                <template v-else>
                  <a-table-summary-cell />
                </template>
              </template>
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>

    <ImportModal ref="importModalRef" @downloadExcel="exportTpl" :import-excel="salesApi.importXlsx" :extra-params="{ type: 1, order_type: 2 }" @reloadList="queryData" />
    <ReturnDetailsModal ref="detailRef" />
    <ReturnPrintModal ref="printRef" />
    <ReturnFormModal ref="formModal" @reloadList="queryData" />
  </a-card>
</template>
<script setup lang="ts">
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import ReturnFormModal from './components/return-form-modal.vue'
import ReturnDetailsModal from './components/return-details-modal.vue'
import ReturnPrintModal from './components/return-print-modal.vue'
import { salesApi } from '@/api/business/sale/sales-api'
import { PAGE_SIZE_OPTIONS, DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import SearchFormCollapse from '@/components/support/search-form-collapse/index.vue'
import Select from '@/components/business/select/index.vue'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import TableOperator from '@/components/support/table-operator/index.vue'
import ImportModal from '@/components/support/import-modal/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import _ from 'lodash'
import { message, Modal } from 'ant-design-vue'
import { errorSentry } from '@/lib/error-sentry'
import { useQuery } from '@/hooks/web/use-query-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { useEnums } from '@/hooks/plugins/useEnums'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useResize } from '@/hooks/web/use-resize-hook'
import { useLoadingStore } from '@/store/modules/loading-store'
import { WAREHOUSE_TYPE, WAREHOUSE_ATTRIBUTE_TYPE } from '@/constants/business/storage/warehouse/warehouse-const'
import { useRoute } from 'vue-router'
import { ref, onMounted } from 'vue'

const route = useRoute()
const appConfigStore = useAppConfigStore()
const loadingStore = useLoadingStore()
const { getDescByValue } = useEnums()
const tagType = ref({
  1: 'error',
  2: 'warning',
  3: 'processing',
  4: 'success',
  5: '',
  6: 'orange',
  7: 'cyan',
  8: 'purple'
})
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY, expand } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = computed(() => [
  {
    title: '单据编号',
    dataIndex: 'no',
    width: appConfigStore.$state.compactFlag ? 150 : 180
  },
  {
    title: '门店名称',
    dataIndex: ['store', 'store_name']
  },
  {
    title: '所属片区',
    dataIndex: ['store', 'region', 'name']
  },
  {
    title: '业务员',
    dataIndex: ['salesman', 'rename']
  },
  {
    title: '入库仓库',
    dataIndex: 'warehouse_name'
  },
  {
    title: '订单类型',
    dataIndex: 'detailAll',
    width: 100
  },
  {
    title: '订单状态',
    dataIndex: 'status',
    width: 100
  },
  {
    title: '订单金额',
    dataIndex: 'detail_sum',
    width: 120
  },
  {
    title: '订单数量',
    dataIndex: 'order_number',
    width: 120
  },
  {
    title: '结算方式',
    dataIndex: 'payment_type_text',
    width: 100
  },
  {
    title: '订单来源',
    dataIndex: 'source',
    width: 100
  },
  {
    title: '配送方式',
    dataIndex: 'is_self',
    width: 100
  },
  {
    title: '订单备注',
    dataIndex: 'remark',
    width: 100
  },
  {
    title: '单据日期',
    dataIndex: 'create_time'
  },
  {
    title: '创建者',
    dataIndex: ['creator', 'username']
  },
  {
    title: '打印次数',
    dataIndex: ['printLog', 'print_count'],
    width: 100
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: appConfigStore.$state.compactFlag ? 150 : 180
  }
])
// ---------------------------- 查询数据表单和方法 ----------------------------
const total_amount = ref({
  total_detail_sum: 0
})
const { queryForm, queryFormOp, tableData, tableLoading, total, resetQuery, onSearch, queryData, deleteData } = useQuery({
  fetchDataApi: async (params) => {
    const res = await salesApi.queryList(params)
    const { data, ...other } = res.data
    total_amount.value = {
      ...other
    }
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  fetchDeleteApi: async (id) => {
    const res = await salesApi.del({ id })
    return !!res
  },
  queryFormFilter: {
    no: '',
    create_time: DEFAULT_TIME_RANGE.value,
    salesman_id: null,
    store_id: null,
    status: null,
    payment_type: null,
    type: 1,
    order_type: 2
  },
  queryFormOp: {
    no: QUERY_FORM_OP['模糊查询'],
    salesman_id: QUERY_FORM_OP['全等查询'],
    create_time: QUERY_FORM_OP['范围查询'],
    store_id: QUERY_FORM_OP['全等查询'],
    status: QUERY_FORM_OP['全等查询'],
    payment_type: QUERY_FORM_OP['全等查询'],
    type: QUERY_FORM_OP['全等查询'],
    order_type: QUERY_FORM_OP['全等查询']
  }
})

onMounted(() => {
  queryForm.value.salesman_id = Number(route.query.salesman_id) || null
  queryForm.value.create_time = route.query.create_time || route.query?.no ? [] : DEFAULT_TIME_RANGE.value
  queryForm.value.no = route.query.no
  queryData()
})

// Select查询参数
const selectFetchParams = {
  warehouse: {
    filter: {
      warehouse_type: WAREHOUSE_TYPE.FIXED.value,
      attribute_type: WAREHOUSE_ATTRIBUTE_TYPE.OTHER.value
    },
    op: {
      warehouse_type: QUERY_FORM_OP['全等查询'],
      attribute_type: QUERY_FORM_OP['不等查询']
    },
    fields: 'id,name'
  }
}

// ---------------------------- 添加/修改 ----------------------------
const formModal = ref()

function addOrder(rowData) {
  formModal.value.showDrawer(rowData)
}

// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = async (rowData) => {
  try {
    const res = await salesApi.detail({ id: rowData.id })
    detailRef.value.showDrawer(res.data)
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  }
}
// ---------------------------- 打印 ----------------------------
const printRef = ref()

const print = async (rowData) => {
  try {
    const res = await salesApi.detail({ id: rowData.id })
    printRef.value.showDrawer(res.data)
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  }
}
// ------------------------------- 导出和导入 ---------------------------------
const importModalRef = ref()
function showImportModal() {
  importModalRef.value.showImportModal()
}
// 导出
function onExport() {
  const { page, limit, ...filter } = queryForm.value
  const data = {
    filter: JSON.stringify(filter),
    op: JSON.stringify(queryFormOp)
  }
  salesApi.exportXlsx(data)
}
// 导入模版
function exportTpl() {
  const data = {
    type: 1,
    order_type: 2
  }
  salesApi.exportTpl(data)
}
// ------------------------------- 订单类型去重 ---------------------------------
const uniqueTypes = (detailList) => {
  // 使用 Set 去重
  const types = new Set(detailList.map((item) => item.type))
  return Array.from(types) // 将 Set 转换为数组
}
// ------------------------------- 取消 ---------------------------------
// 取消
function returnCancel(rowData) {
  Modal.confirm({
    title: '提示',
    content: '确定要取消【' + rowData.no + '】吗?',
    okText: '确定',
    okType: 'danger',
    onOk() {
      singleCancel(rowData)
    },
    cancelText: '取消',
    onCancel() {}
  })
}

async function singleCancel(rowData) {
  try {
    loadingStore.show()
    const res = await salesApi.cancel(rowData.id)
    message.success(res.msg)
    queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}
</script>
<style scoped>
.ant-table-striped :deep(.table-striped) td {
  background-color: #fafafa;
  color: #b9b9b9;
}
</style>
